<template>
  <div class="login-wrapper">
    <div class="form-box">
      <div class="form-title">
        <img src="../../assets/img/login/logo.png" alt="icon"/>
        <p>账号登录</p>
      </div>

      <!--
      ref 属性涉及Dom 元素的获取(el-form表单对象)
      -->
      <el-form ref="loginForm" :model="loginForm" :rules="loginRules" class="login-form" label-width="80px">

        <div class="el switch">
          <el-form-item>
            <el-switch
                v-model="loginForm.option"
                active-text="管理员登录"
                active-value="1"
                inactive-text="用户/骑手登录"
                inactive-value="0"
                inactive-color="#13ce66"
                style="float: left;margin-top: 10px">
            </el-switch>
          </el-form-item>
        </div>

        <!--
        可以通过<div class="form-input"控制输入框样式，比如输入框的长度、宽度之类的样式（可以在style中的.form-input中进行修改）
        -->

        <!--用户登录-->
        <div v-if="loginForm.option==='0'">
          <div class="form-input">
            <el-form-item prop="telephone" label="电话">
              <el-input v-model.number="loginForm.telephone" type="text"
                        auto-complete="off" prefix-icon="el-icon-user"
                        placeholder="请输入电话号码" clearable/>
            </el-form-item>

            <el-form-item prop="password" label="密码">
              <el-input v-model.trim="loginForm.password" type="password"
                        auto-complete="off" placeholder="请输入密码"
                        prefix-icon="el-icon-lock" show-password
                        @keyup.enter.native="handleUserLogin"/>
            </el-form-item>

            <el-form-item label="验证码" prop="code">
              <el-input v-model.trim="loginForm.code" prefix-icon="el-icon-s-opportunity"
                        style="width: 172px;float: left" placeholder="请输入验证码"></el-input>
              <canvas id="canvas" width="130px" height="35px" @click="handleCanvas"></canvas>
            </el-form-item>
          </div>

          <!--
          可以通过<div class="form-button"控制按钮样式，比如按钮的长度、宽度之类的样式（可以在style中的.form-button中进行修改）
          -->
          <div class="form-button">
            <el-form-item>
              <el-button :loading="loading" type="primary" @click="handleUserLogin()">
                <span v-if="!loading">登 录</span>
                <span v-else>登 录 中...</span>
              </el-button>
              <el-button @click="jumpToRegister()" type="primary">注 册</el-button>
              <el-button @click="returnBackground()" type="primary">返 回</el-button>
            </el-form-item>
          </div>
        </div>

        <!--管理员登录-->
        <div v-if="loginForm.option==='1'">
          <div class="form-input">
            <el-form-item prop="administratorId" label="账号">
              <el-input v-model.number="loginForm.administratorId" type="text"
                        auto-complete="off" prefix-icon="el-icon-user"
                        placeholder="请输入管理员账号" clearable/>
            </el-form-item>

            <el-form-item prop="administratorPassword" label="密码">
              <el-input v-model.trim="loginForm.administratorPassword" type="password"
                        auto-complete="off" placeholder="请输入管理员密码"
                        prefix-icon="el-icon-lock" show-password
                        @keyup.enter.native="handleAdministratorLogin"/>
            </el-form-item>

            <el-form-item label="验证码" prop="code">
              <el-input v-model.trim="loginForm.code" prefix-icon="el-icon-s-opportunity"
                        style="width: 172px;float: left" placeholder="请输入验证码"></el-input>
              <canvas id="canvas1" width="130px" height="35px" @click="handleCanvas1"></canvas>
            </el-form-item>
          </div>

          <!--
          可以通过<div class="form-button"控制按钮样式，比如按钮的长度、宽度之类的样式（可以在style中的.form-button中进行修改）
          -->
          <div class="form-button">
            <el-form-item>
              <el-button :loading="loading" type="primary" @click="handleAdministratorLogin()">
                <span v-if="!loading">登 录</span>
                <span v-else>登 录 中...</span>
              </el-button>
              <el-button @click="returnBackground()" type="primary">返 回</el-button>
            </el-form-item>
          </div>
        </div>

      </el-form>
    </div>

    <!--
    背景图
    -->
    <div class="background" id="background"></div>
    <div class="yinghua" id="yinghua"></div>
    <canvas class="fireworks"
            style="position: fixed; left: 0; top: 0; z-index: 99999999; pointer-events: none;"></canvas>
  </div>
</template>

<script>
/**
 * 引入main.js中load2D_bg()、load2D_bg2_2()、load2D_yinghua()、load2D_bg2_2()方法
 */
import {load2D_bg, load2D_yinghua, load2D_bg2, load2D_bg2_2} from "@/api/background";
/**
 * 引入jQuery
 */
import $ from "jquery"

/**
 * 引入login.js中的login()方法
 */
import {login, administratorLogin} from "@/api/login";

/**
 * 引入cookie.js中的setToken()方法
 */
import {setToken} from "@/utils/cookie";
import {setAdministratorToken} from "@/utils/cookie";
import {setAdministratorInformation} from "@/api/administrator";
import {setUserInformation} from "@/api/user";


export default {
  name: "Login",

  data() {
    return {
      true_code: "",//保存正确的验证码
      arr: [],//用于传参

      /**
       * loginForm：登录的属性名
       */
      loginForm: {
        /**
         * telephone、password：用户登录需要的信息
         */
        telephone: '', //电话号码
        password: '', //密码

        /**
         * administratorID、administratorPassword：管理员登录需要的信息
         */
        administratorId: '', // 管理员账号
        administratorPassword: '', //管理员密码

        code: '', //验证码

        /**
         * option：选择用户登录/管理员登录
         */
        option: '0', //0：用户/骑手登录；1：管理员登录
      },

      /**
       * 登录验证规则（密码正则表达式待定）
       */
      loginRules: {
        telephone: [{required: true, trigger: 'blur', message: '电话不能为空'},
          {pattern: /^1[3|4|5|7|8][0-9]{9}$/, message: '请输入注册账号的手机号码，共11位'}],
        password: [{required: true, trigger: 'blur', message: '密码不能为空'},
          {min: 6, max: 12, pattern: /^[A-Za-z][A-Za-z0-9_]{5,12}$/, message: '密码为6-12位，且第1位是字母'}],
        code: [{required: true, trigger: 'blur', message: '验证码不能为空'},
          {min: 4, max: 4, message: '长度在4个字符', trigger: 'blur'}],
        administratorId: [{required: true, trigger: 'blur', message: '管理员账号不能为空'},
          {pattern: /^2019[0-9]{6}$/, message: '请输入管理员账号，共10位'}],
        administratorPassword: [{required: true, trigger: 'blur', message: '管理密码不能为空'},
          {min: 6, max: 12, pattern: /^[A-Za-z][A-Za-z0-9_]{5,11}$/, message: '密码为6-12位，且第1位是字母'}],
      },

      /**
       * 按钮是否是加载中状态
       */
      loading: false,
    }
  },

  mounted() {
    this.draw(this.arr);
  },

  beforeCreate() {
    $(document).ready(function () {
      window.onload = load2D_bg();
      window.onload = load2D_bg2();
      window.onload = load2D_bg2_2();
      window.onload = load2D_yinghua();
    })
  },

  methods: {
    /**
     * 处理用户登录，验证成功则跳转到个人用户/商家用户页面
     */
    handleUserLogin() {
      this.$refs.loginForm.validate(valid => {
        const data = {
          telephone: this.loginForm.telephone,
          password: this.loginForm.password
        };

        /**
         * 通过登录验证规则
         */
        if (valid) {
          this.loading = true;
          /**
           * 验证码验证,通过则提交账号密码验证，否则重新验证验证码
           */
          if(this.loginForm.code === this.true_code) {
            /**
             * telephone和密码验证
             */
            login(data).then(res => {
              if (res.message === "验证成功") {
                this.loading = false;

                /**
                 * token和administratorToken不能同时为true
                 */
                setToken(true);
                setAdministratorToken(false);
                setUserInformation(res.user);
                this.$router.push({
                  path: "/home"
                });
              } else if (res.message === "对不起，此账号虽然已经注册但管理员尚未审核") {
                this.loading = false;
                this.$message({
                  message: "对不起，此账号虽然已经注册但管理员尚未审核",
                  type: "info"
                })
              } else if (res.message === "对不起，此账号虽然已经注册但管理员尚未审核") {
                this.loading = false;
                this.$message({
                  message: "对不起，此账号虽然已经注册但没有通过管理员的审核",
                  type: "warning"
                })
              } else if (res.message === "您输入的电话号码或密码有误，请重新输入") {
                this.loading = false;
                this.$message({
                  message: "您输入的电话号码或密码有误，请重新输入",
                  type: "error"
                })
              } else if (res.message === "对不起，此账号的状态的为已禁用") {
                this.loading = false;
                this.$message({
                  message: "对不起，此账号的状态的为已禁用",
                  type: "error"
                })
              }
            }).catch(() => {
              this.loading = false;
            })
          }else {
            this.$message.error("验证码错误")
            this.handleCanvas()
            this.loading = false
          }
        }
      })
    },

    /**
     * 处理管理员登录,验证成功则跳转到管理员页面
     */
    handleAdministratorLogin() {
      this.$refs.loginForm.validate(valid => {
        const data = {
          administratorId: this.loginForm.administratorId,
          password: this.loginForm.administratorPassword
        };
        if(this.loginForm.code === this.true_code){
          /**
           * 通过登录验证规则
           */
          if (valid) {
            this.loading = true;

            /**
             * 管理员账号和密码验证
             */
            administratorLogin(data).then(res => {
              if (res.message === "验证成功") {
                this.loading = false;
                setAdministratorToken(true);
                setToken(false);

                setAdministratorInformation(data.administratorId);
                this.$router.push({
                  path: "/administration",
                });
              } else if (res.message === "您输入的管理员账号或密码有误，请重新输入") {
                this.loading = false;
                this.$message({
                  message: "您输入的管理员账号或密码有误，请重新输入",
                  type: "error"
                })
              }
            }).catch(() => {
              this.loading = false;
            })
          }else{
            this.$message.error("验证码错误")
            this.handleCanvas()
            this.loading = false
          }
        }
      })
    },

    /**
     * 跳转至注册页面
     */
    jumpToRegister() {
      this.$router.push("/register")
    },

    /**
     * 返回背景页面
     */
    returnBackground() {
      this.$router.push({
        path: "/background"
      })
    },

    /**
     * 验证码功能
     */
    //显示验证码区域内容信息
    draw(show_num) {
      let i;
      // 依次把取得的内容放到数组里面
      let x;
      //文字在canvas上的x坐标
      let y;
      const canvas_width = document.querySelector("#canvas").clientWidth;
      let canvas_height = document.querySelector("#canvas").clientHeight;
      const canvas = document.getElementById("canvas"); //获取到canvas
      const context = canvas.getContext("2d"); //获取到canvas画图
      canvas.width = canvas_width
      canvas.height = canvas_height
      const sCode = "a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z," +
          "A,B,C,E,F,G,H,J,K,L,M,N,P,Q,R,S,T,W,X,Y,Z,1,2,3,4,5,6,7,8,9,0";
      const aCode = sCode.split(",");
      const aLength = aCode.length; //获取到数组的长度

      //4个验证码数
      for (i = 0; i <= 3; i++) {
        const j = Math.floor(Math.random() * aLength); //获取到随机的索引值
        const deg = (Math.random() * 30 * Math.PI) / 180; //产生0~30之间的随机弧度
        const txt = aCode[j]; //得到随机的一个内容
        show_num[i] = txt.toLowerCase();
        x = 10 + i * 20;
        y = 20 + Math.random() * 8; //文字在canvas上的y坐标
        context.font = "bold 23px 微软雅黑";

        context.translate(x, y);
        context.rotate(deg);

        context.fillStyle = this.randomColor();
        context.fillText(txt, 0, 0);

        context.rotate(-deg);
        context.translate(-x, -y);
      }
      //验证码上显示6条线条
      for (i = 0; i <= 5; i++) {
        context.strokeStyle = this.randomColor();
        context.beginPath();
        context.moveTo(
            Math.random() * canvas_width,
            Math.random() * canvas_height
        );
        context.lineTo(
            Math.random() * canvas_width,
            Math.random() * canvas_height
        );
        context.stroke();
      }
      //验证码上显示31个小点
      for (i = 0; i <= 30; i++) {
        context.strokeStyle = this.randomColor();
        context.beginPath();
        x = Math.random() * canvas_width;
        y = Math.random() * canvas_height;
        context.moveTo(x, y);
        context.lineTo(x + 1, y + 1);
        context.stroke();
      }

      //最后把取得的验证码数组存起来，方式不唯一
      const num = show_num.join("");
      // console.log(num);
      this.true_code = num
    },

    //得到随机的颜色值
    randomColor() {
      const r = Math.floor(Math.random() * 256);
      const g = Math.floor(Math.random() * 256);
      const b = Math.floor(Math.random() * 256);
      return "rgb(" + r + "," + g + "," + b + ")";
    },

    //canvas点击刷新
    handleCanvas() {
      this.loginForm.code = '' //刷新时，输入框置为空
      this.draw(this.arr);
    },

    /**
     * 验证码功能_管理员登录
     */
    //显示验证码区域内容信息
    draw1(show_num) {
      let i;
      // 依次把取得的内容放到数组里面
      let x;
      //文字在canvas上的x坐标
      let y;
      const canvas_width = document.querySelector("#canvas1").clientWidth;
      let canvas_height = document.querySelector("#canvas1").clientHeight;
      const canvas = document.getElementById("canvas1"); //获取到canvas
      const context = canvas.getContext("2d"); //获取到canvas画图
      canvas.width = canvas_width
      canvas.height = canvas_height
      const sCode = "a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z," +
          "A,B,C,E,F,G,H,J,K,L,M,N,P,Q,R,S,T,W,X,Y,Z,1,2,3,4,5,6,7,8,9,0";
      const aCode = sCode.split(",");
      const aLength = aCode.length; //获取到数组的长度

      //4个验证码数
      for (i = 0; i <= 3; i++) {
        const j = Math.floor(Math.random() * aLength); //获取到随机的索引值
        const deg = (Math.random() * 30 * Math.PI) / 180; //产生0~30之间的随机弧度
        const txt = aCode[j]; //得到随机的一个内容
        show_num[i] = txt.toLowerCase();
        x = 10 + i * 20;
        y = 20 + Math.random() * 8; //文字在canvas上的y坐标
        context.font = "bold 23px 微软雅黑";

        context.translate(x, y);
        context.rotate(deg);

        context.fillStyle = this.randomColor();
        context.fillText(txt, 0, 0);

        context.rotate(-deg);
        context.translate(-x, -y);
      }
      //验证码上显示6条线条
      for (i = 0; i <= 5; i++) {
        context.strokeStyle = this.randomColor();
        context.beginPath();
        context.moveTo(
            Math.random() * canvas_width,
            Math.random() * canvas_height
        );
        context.lineTo(
            Math.random() * canvas_width,
            Math.random() * canvas_height
        );
        context.stroke();
      }
      //验证码上显示31个小点
      for (i = 0; i <= 30; i++) {
        context.strokeStyle = this.randomColor();
        context.beginPath();
        x = Math.random() * canvas_width;
        y = Math.random() * canvas_height;
        context.moveTo(x, y);
        context.lineTo(x + 1, y + 1);
        context.stroke();
      }

      //最后把取得的验证码数组存起来，方式不唯一
      const num = show_num.join("");
      // console.log(num);
      this.true_code = num
    },

    //得到随机的颜色值
    randomColor1() {
      const r = Math.floor(Math.random() * 256);
      const g = Math.floor(Math.random() * 256);
      const b = Math.floor(Math.random() * 256);
      return "rgb(" + r + "," + g + "," + b + ")";
    },

    //canvas点击刷新
    handleCanvas1() {
      this.loginForm.code = '' //刷新时，输入框置为空
      this.draw1(this.arr);
    },
  }
}

</script>

<style lang="less">
@import "../../assets/less/background";

.login-wrapper {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100vh;

  .form-box {
    width: 450px;
    height: 500px;
    opacity: 0.9;
    padding: 15px 30px 20px;
    background: white;
    border-radius: 25px;

    .form-title {
      margin: 0 auto 35px;
      text-align: center;
      color: #707070;
      font-size: 18px;
      letter-spacing: 2px;
    }

    /**
    * 可以通过.form-input控制输入框样式
    */

    .form-input {
      width: 400px;
    }

    /**
    * 可以通过.form-button控制按钮样式
    */

    .form-button {
      float: right;
    }
  }
}

img {
  width: 100px;
  height: 100px;
}

#canvas {
  float: right;
  margin-right: 0;
  display: block;
  border: 1px solid #ccc;
  border-radius: 5px;
  cursor: pointer;
}

#canvas1 {
  float: right;
  margin-right: 0;
  display: block;
  border: 1px solid #ccc;
  border-radius: 5px;
  cursor: pointer;
}


</style>
